import socket
import threading
from com_process import process_socket_save

# 线程安全的连接列表管理
connections = []
conn_lock = threading.Lock()

def socket_send_data(client_sock, message):
    """
    发送数据接口（线程安全）
    :param client_sock: 要发送的客户端套接字
    :param message: 发送的字符串消息
    """
    try:
        client_sock.sendall(message.encode('utf8'))
    except (ConnectionError, OSError) as e:
        print(f"发送失败: {e}")
        return False
    return True

def handle_client(client_sock, client_addr):
    """
    客户端连接处理线程（接收数据并打印）
    :param client_sock: 客户端套接字对象
    :param client_addr: 客户端地址(ip, port)
    """
    try:
        print(f"[+] 新连接: {client_addr}")
        while True:
            data = client_sock.recv(1024)  # 接收数据

            if not data:  # 连接断开时退出循环
                break
            print(f"来自 {client_addr} 的数据: {data.decode('utf8')}")
            process_socket_save(data, client_sock)
            # socket_send_data(client_sock, "{\"set\":\"vs\"}\r\n") # 作为调试使用！！！！!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! vs是参观模式 wr是报警模式

    except ConnectionResetError:
        print(f"[-] 连接被客户端重置: {client_addr}")
    finally:
        with conn_lock:  # 线程安全移除连接
            if client_sock in connections:
                connections.remove(client_sock)
        client_sock.close()
        print(f"[-] 连接关闭: {client_addr}")

def socket_start_server():
    """
    启动多线程Socket服务器
    :param host: 监听地址
    :param port: 监听端口
    """

    host='0.0.0.0'
    port=8080

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 端口复用
    server.bind((host, port))
    server.listen(50)
    print(f"[*] 服务器已启动 {host}:{port}")

    try:
        while True:
            client, addr = server.accept()
            with conn_lock:
                connections.append(client)
            # 为每个连接创建新线程
            threading.Thread(target=handle_client, args=(client, addr)).start()
    except KeyboardInterrupt:
        print("\n[!] 服务器关闭中...")
    finally:
        server.close()



if __name__ == '__main__':
    socket_start_server()